//
//  StudentsEnjoyableViewController.m
//  ECBBusinessCamp
//
//  Created by rimi on 16/6/16.
//  Copyright © 2016年 邓毕华. All rights reserved.
//

#import "StudentsEnjoyableViewController.h"

#define StudentsEnjoyableTableViewCellIdentifier @"studentsEnjoyableTableViewCellIdentifier"

#import "RadioButtonsView.h"
#import "StudentsEnjoyableTableViewCell.h"
#import "StudentsEnjoyableDetailViewController.h"
#import "StudentsEnjoyableAddViewController.h"

@interface StudentsEnjoyableViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) RadioButtonsView * radioButtonsView; // 单行按钮组
@property (nonatomic, strong) UIButton * releaseButton; // 发布尊享按钮
@property (nonatomic, strong) UITableView * studentsEnjoyableTableView; // 同学尊享表格视图
@property (nonatomic, strong) NSMutableDictionary * parameters; // 网络请求参数
@property (nonatomic, assign) NSInteger pageNum; // 记录列表页码
@property (nonatomic, strong) NSMutableArray * dataSource; // 网络请求下来的数据

@end

@implementation StudentsEnjoyableViewController

#pragma mark 🌷🌷🌷life cycle🌷🌷🌷
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];

    // 添加子视图
    [self.view addSubview:self.radioButtonsView];
    [self.view addSubview:self.releaseButton];
    [self.view addSubview:self.studentsEnjoyableTableView];
    
    // 自动布局
    [_radioButtonsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.sizeOffset(CGSizeMake(SCREEN_WIDTH * 0.08 * 2 + SCREEN_WIDTH * 0.02, SCREEN_WIDTH * 0.08 * 0.5));
        make.centerX.equalTo(self.view);
        make.top.offset(SCREEN_HEIGHT * 0.113);
    }];
    [_releaseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(_radioButtonsView);
        make.width.offset(SCREEN_WIDTH * 0.18);
        make.centerY.equalTo(_radioButtonsView);
        make.right.offset(SCREEN_WIDTH * -0.03);
    }];
    [_studentsEnjoyableTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view);
        make.top.equalTo(_releaseButton.mas_bottom);
        make.centerX.equalTo(self.view);
        make.bottom.offset(SCREEN_HEIGHT * -0.09);
    }];
    
    // 添加刷新
    [self addRefresh];
    // 注册单元格
    [self.studentsEnjoyableTableView registerClass:[StudentsEnjoyableTableViewCell class] forCellReuseIdentifier:StudentsEnjoyableTableViewCellIdentifier];
    // 设置单元格高度
    _studentsEnjoyableTableView.rowHeight = SCREEN_HEIGHT * 0.3;
    
    // 第一次网络请求
    self.parameters[@"read"] = _radioButtonsView.selecIndex == 10 ? @"all" : @"self";
    _pageNum = 0;
    [self loadData];
    
}

#pragma mark 🌷🌷🌷UITableViewDataSource🌷🌷🌷
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    StudentsEnjoyableTableViewCell * cell = [_studentsEnjoyableTableView dequeueReusableCellWithIdentifier:StudentsEnjoyableTableViewCellIdentifier forIndexPath:indexPath];
    
    if (self.dataSource[indexPath.row]) {
        cell.mainView.eid = _dataSource[indexPath.row][@"id"];
        [cell.mainView.leftImageView sd_setImageWithURL:[NSURL URLWithString:BASEURLAPPEND(_dataSource[indexPath.row][@"pic"])] placeholderImage:[UIImage imageNamed:@"default_head.png"]];
        cell.mainView.themeLabel.text = [NSString stringWithFormat:@"尊享主题：%@", _dataSource[indexPath.row][@"title"]];
        cell.mainView.originatorLabel.text = [NSString stringWithFormat:@"发起人：%@", _dataSource[indexPath.row][@"fromuser"]];
        cell.mainView.deadlineLabel.text = [NSString stringWithFormat:@"截止日期：%@", [DateFormatter getDateSince1970BySeconds:[_dataSource[indexPath.row][@"endtime"][@"time"] integerValue]]];
        cell.mainView.numberPeopleLabel.text = [NSString stringWithFormat:@"已有%@人参加", _dataSource[indexPath.row][@"joinNum"]];
        cell.mainView.joinButton.userInteractionEnabled = [_dataSource[indexPath.row][@"enjoyover"] isEqualToString:@"0"] ? YES : NO;
        cell.mainView.joinButton.hidden = [_dataSource[indexPath.row][@"fromuser"] isEqualToString:[LoginUserInfo defaultUserInfo].username] ? YES : NO;
        cell.mainView.overdueImageView.hidden = [_dataSource[indexPath.row][@"enjoyover"] isEqualToString:@"0"] || [_dataSource[indexPath.row][@"fromuser"] isEqualToString:[LoginUserInfo defaultUserInfo].username] ? YES : NO;
    }
    
    return cell;
}

#pragma mark 🌷🌷🌷UITableViewDelegate🌷🌷🌷
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 添加详细视图与控制器
    StudentsEnjoyableDetailViewController * studensEnjoyableDetailVc = [[StudentsEnjoyableDetailViewController alloc] init];
    studensEnjoyableDetailVc.view.frame = CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    studensEnjoyableDetailVc.eid = _dataSource[indexPath.row][@"id"];
    [self addChildViewController:studensEnjoyableDetailVc];
    [self.view addSubview:studensEnjoyableDetailVc.view];
    // 动画
    [UIView animateWithDuration:0.5 animations:^{
        studensEnjoyableDetailVc.view.center = CGPointMake(SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.5);
    }];
}

#pragma mark 🌷🌷🌷event response🌷🌷🌷
- (void)respondsToReleaseBtn:(UIButton *)sender {
    // 添加发布尊享视图与控制器
    StudentsEnjoyableAddViewController * studentsEnjoyableAddVc = [[StudentsEnjoyableAddViewController alloc] init];
    studentsEnjoyableAddVc.type = 0;
    [self addChildViewController:studentsEnjoyableAddVc];
    [self.view addSubview:studentsEnjoyableAddVc.view];
}

#pragma mark 🌷🌷🌷private methods🌷🌷🌷
- (void)addRefresh {
    _studentsEnjoyableTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 下拉刷新
        self.parameters[@"read"] = _radioButtonsView.selecIndex == 10 ? @"all" : @"self";
        _pageNum = 0;
        [self.dataSource removeAllObjects];
        [self loadData];
    }];
    _studentsEnjoyableTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        // 下拉加载更多
        if (_dataSource.count < (_pageNum + 1) * 10) {
            [MBProgressHUD showError:@"没有更多数据！"];
            [_studentsEnjoyableTableView.mj_footer endRefreshing];
            return ;
        }
        _pageNum += 1;
        [self loadData];
    }];
}
- (void)loadData {
    self.parameters[@"pageNum"] = @(_pageNum);
    [[NetTool sharedTool] requestMethod:POST loadingMsg:@"加载中..." url:BASEURLAPPEND(STUDENTSENJOYABLE_URL) parameters:_parameters finish:^(id responseObject, NSError *error) {
        if (!error) {
            [MBProgressHUD showSuccess:@"加载完成！"];
            [self.dataSource addObjectsFromArray:responseObject[@"data"]];
            [_studentsEnjoyableTableView reloadData];
        } else {
            [MBProgressHUD showError:[[NSString stringWithFormat:@"%@", error] containsString:@"The request timed out."] ? @"登录超时" : @"I don't know"];
        }
        [_studentsEnjoyableTableView.mj_header endRefreshing];
        [_studentsEnjoyableTableView.mj_footer endRefreshing];
    }];
}

#pragma mark 🌷🌷🌷getters and setters🌷🌷🌷
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
- (RadioButtonsView *)radioButtonsView {
    if (!_radioButtonsView) {
        NSArray * titleNames = @[@"所有", @"个人"];
        _radioButtonsView = [[RadioButtonsView alloc] initWithNames:titleNames selectedIndex:^(NSInteger selectIndex) {
            self.parameters[@"read"] = selectIndex == 0 ? @"all" : @"self";
            [_studentsEnjoyableTableView.mj_header beginRefreshing];
        }];
    }
    return _radioButtonsView;
}
- (UIButton *)releaseButton {
    if (!_releaseButton) {
        _releaseButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _releaseButton.backgroundColor = RGB_COLOR(1, 157, 173, 1);
        [_releaseButton setTitle:@"+发布尊享" forState:UIControlStateNormal];
        _releaseButton.titleLabel.font = [UIFont systemFontOfSize:25];
        [_releaseButton addTarget:self action:@selector(respondsToReleaseBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _releaseButton;
}
- (UITableView *)studentsEnjoyableTableView {
    if (!_studentsEnjoyableTableView) {
        _studentsEnjoyableTableView = [[UITableView alloc] init];
        // 设置数据源
        _studentsEnjoyableTableView.dataSource = self;
        // 设置代理
        _studentsEnjoyableTableView.delegate = self;
        // 去掉分隔线
        _studentsEnjoyableTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _studentsEnjoyableTableView;
}
- (NSMutableDictionary *)parameters {
    if (!_parameters) {
        _parameters = [NSMutableDictionary dictionaryWithObjects:@[@"all", @(0), @(10)] forKeys:@[@"read", @"pageNum", @"pagesize"]];
    }
    return _parameters;
}

@end
